package com.funtl.screw.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.funtl.screw.admin.entity.SysUser;
import com.funtl.screw.admin.mapper.SysUserMapper;
import com.funtl.screw.admin.service.MobileService;
import com.funtl.screw.common.core.constant.CacheConstants;
import com.funtl.screw.common.core.constant.SecurityConstants;
import com.funtl.screw.common.core.util.ResponseResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 手机登录相关业务实现
 *
 * @author lusifer
 */
@Slf4j
@Service
@AllArgsConstructor
@SuppressWarnings("all")
public class MobileServiceImpl implements MobileService {

    private final RedisTemplate redisTemplate;

    private final SysUserMapper userMapper;

    /**
     * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
     *
     * @param mobile mobile
     * @return code
     */
    @Override
    public ResponseResult<Boolean> sendSmsCode(String mobile) {
        List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, mobile));
        if (CollUtil.isEmpty(userList)) {
            log.info("手机号未注册:{}", mobile);
            return ResponseResult.ok(Boolean.FALSE, "手机号未注册");
        }
        Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + mobile);
        if (codeObj != null) {
            log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
            return ResponseResult.ok(Boolean.FALSE, "验证码发送过频繁");
        }
        String code = RandomUtil.randomNumbers(SecurityConstants.CODE_SIZE);
        log.debug("手机号生成验证码成功:{},{}", mobile, code);
        redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
        return ResponseResult.ok(Boolean.TRUE, code);
    }

}
